<template>
  <view class="flex-box-page">
    <!-- <NavBar :title="toUserInfo.nickname"></NavBar> -->
    <view class="chat-list safe-box">
      <List :scrollTop="scrollTop" @scrolltolower="scrolltolower">
        <view class="chat-item" :class="isMyMsg(item.fromUser._id) ? 'right' : 'left'" v-for="item in msgList"
          :key="item._id">
          <view class="main">
            <view class="user">
              <u-avatar size="36" :src="joinDomain(item.fromUser.avatar)">
              </u-avatar>
              <!-- <text class="name">小猪</text> -->
            </view>
            <view class="content">
              <view class="bg">
                <text :selectable="true" :user-select="true">{{item.content}}</text>
              </view>
            </view>
          </view>
          <view class="note" v-if="isMyMsg(item.fromUser._id)">{{item.isRead ? '已读' : '未读'}}</view>
        </view>
      </List>
    </view>
    <view class="fixed-bottom">
      <view class="inp-box">
        <u--textarea placeholder="请输入内容" v-model="sendContent" autoHeight count :maxlength="100" confirmType="done" :cursorSpacing="20">
        </u--textarea>
      </view>
      <view class="btn-box">
        <u-button @click="send" text="发送" type="success" size="middle"></u-button>
      </view>
    </view>
  </view>
</template>

<script>
  import eventBus from '@/eventbus/index.js'
  export default {
    data() {
      return {
        toUserInfo: {},
        sendContent: '',
        // socket: null,
        msgList: [],
        scrollTop: 0,
        timer: null
      }
    },
    computed: {
      user() {
        return this.$store.state.user
      },
      isMyMsg() {
        return (id) => this.user._id === id
      },
      // 微信小程序这样使用会报错
      // socket() {
      //   return this.$store.state.socket
      // },
      newMsg() {
        return this.$store.state.onlineMsg
      }
    },
    watch: {
      newMsg(newVal) {
        // 是当前窗口聊天好友的消息才加入
        if(newVal.fromUser._id === this.toUserInfo._id) {
          this.msgList.push(newVal)
          this.resetScroll()
        }
      }
    },
    methods: {
      send() {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          if(this.sendContent === '') {
            this.$tip.showToast('请输入发送内容')
          } else if(!this.$store.state.socket) {
            console.log(this.$store.state.socket)
            this.$tip.showToast('连接已中断，无法发送消息，请刷新稍后再试')
          } else {
            this.$store.state.socket.emit('chat', {
              fromUser: this.$store.state.user._id,
              toUser: this.toUserInfo._id,
              content: this.sendContent,
              // isRead: true
            })
          }
          this.canSend = true
        }, 20)
      },
      async getHistoryMsg() {
        const res = await this.$http.get(`/chat/${this.toUserInfo._id}`)
        this.msgList = res.data
        this.resetScroll()
      },
      initSocket() {
        // 监听自己发送的消息是否成功
        if (this.$store.state.socket) {
          this.$store.state.socket.on('success', (data) => {
            // 收到服务器推送的消息，可以跟进自身业务进行操作
            console.log('success：', data);
            // 成功发送，清空输入框
            this.sendContent = ''
            this.msgList.push(data)
            this.resetScroll()
            this.$store.commit('sendMsgSuccess', data)
          });
        }
      },
      scrolltolower() {
        // console.log(this.scrollTop)
      },
      resetScroll() {
        this.scrollTop--
        this.$nextTick(() => {
          this.scrollTop = 9999
        })
      }
    },
    mounted() {
      this.getHistoryMsg()
      uni.setNavigationBarTitle({
      	title: this.toUserInfo.nickname
      });
    },
    onShow() {
      // 每次显示页面则执行监听事件，否则在当前页面隐藏到后台断了连接，再进来连接上也没有当前页面的监听事件了
      // this.initSocket()
      if(this.$store.state.socket) {
        this.$store.state.socket.emit('enter', {
          fromUser: this.user._id,
          toUser: this.toUserInfo._id
        })
      }
    },
    onLoad(query) {
      console.log('query',query)
      this.toUserInfo = {
        ...query
      }
      this.initSocket()
    },
    beforeDestroy() {
      console.log('beforeDestroy')
      // 页面销毁前取消监听
      if (this.$store.state.socket) {
        this.$store.state.socket.off('success')
        this.$store.state.socket.emit('leave', {
          fromUser: this.user._id,
          toUser: this.toUserInfo._id
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .chat-list {
    flex: 1;
    // overflow-y: auto;

    .chat-item {
      margin-bottom: 20rpx;
      .main{
        display: flex;
        align-items: center;
        .user {
          .name {
            margin-left: 10rpx;
          }
        }
        .content {
          // display: inline-block;
          // 清除浮动
          overflow: hidden;
          font-size: 32rpx;
          .bg {
            display: inline-block;
            background-color: #55aa7f;
            color: #fff;
            padding: 10rpx 20rpx;
            border-radius: 20rpx;
          }
        }
      }
      .note{
        text-align: right;
        margin-right: 86rpx;
        margin-top: 10rpx;
      }
    }

    .left {
      .content{
        margin-left: 10rpx;
      }
    }

    .right {
      .main{
        // justify-content: flex-end;
        // 反方向
        flex-flow: row-reverse;
        .content{
          margin-right: 10rpx;
          .bg {
            float: right;
            background-color: #00aaff !important;
          }
        }
      }
    }
  }

  .fixed-bottom {
    // position: fixed;
    // left: 0;
    // right: 0;
    // bottom: 0;
    display: flex;
    background-color: aliceblue;
    padding: 30rpx;

    .inp-box {
      flex: 4;
    }

    .btn-box {
      flex: 1;
      margin-left: 20rpx;
      // height: 100%;
      ::v-deep .u-button {
        height: 100%;
      }
    }
  }
</style>
